<?php

/**
 * File: NotificationBehavior.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/21 17:30
 */

namespace Common\Behavior;

use Common\Extend\DingTalk\Message\DingTalkMessage;
use Think\Behavior;

/**
 * 通知事件类
 * @package Common\Behavior
 */
class NotificationBehavior extends Behavior
{
    protected $sendType;//通知类型:钉钉、sms等
    protected $msgType;//消息类型
    protected $msgName;//消息名称
    protected $msgParam;//消息参数

    /**
     * run
     * @param mixed $params
     * @return  bool
     */
    public function run(&$params)
    {
        $parse = $this->parseParam($params);
        if (!$parse) {
            //解析失败不执行
            return false;
        }
        //发送消息
        foreach ($this->sendType as $item) {
            $this->sendMessage($item);
        }

    }

    /**
     * 解析参数
     * @param $param
     * @return bool;
     */
    protected function parseParam($param)
    {
        //通知类型
        if (empty($param['send_type'])) {
            return false;
        }
        $this->sendType = $param['send_type'];
        //消息类型
        if (empty($param['msg_type'])) {
            return false;
        }
        $this->msgType = $param['msg_type'];
        //消息名称
        if (empty($param['msg_name'])) {
            return false;
        }
        $this->msgName = $param['msg_name'];
        //消息参数
        if (empty($param['msg_param'])) {
            return false;
        }
        $this->msgParam = $param['msg_param'];
        return true;

    }


    /**
     * 发送消息
     * @param $sendType
     */
    protected function sendMessage($sendType)
    {
        //暂时只有钉钉
        if ($sendType == 'dingtalk') {
            DingTalkMessage::handle($this->msgType, $this->msgName, $this->msgParam);
        }

    }

}